﻿using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

using Common;
using Authentication.User;
namespace BuyRequest
{
    partial class EditBuyRequest : PortalModuleBase
    {
        #region Private Members

        private int currentItemId
        {
            get 
            {
                int tmp =Null.NullInteger;
                if (int.TryParse(lblCurRequestId.Text,out tmp))
                    return tmp; 
                return Null.NullInteger;
            }
            set 
            {
                lblCurRequestId.Text = value.ToString();
            }
        }
        ArrayList productCatDsSource = new ArrayList();
        private data.applicationDataSetTableAdapters.tm_buy_requestTA buy_requestTA = new data.applicationDataSetTableAdapters.tm_buy_requestTA();
        private data.applicationDataSet.tm_buy_requestDataTable buy_requestTbl = new data.applicationDataSet.tm_buy_requestDataTable();
        private data.applicationDataSet.tm_buy_requestRow buy_requestRow;
        private int loginUserType
        {
            get
            {
                if (Session["loginUserType"] == null) return 0;
                return (int)Session["loginUserType"];
            }
        }
        #endregion

        #region Event Handlers

        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                txtNgayDangKy.BackColor = systemSettings.sysColorDisableBG;
                txtNgayCapnhat.BackColor = systemSettings.sysColorDisableBG;
                txtNguoiDangKy.BackColor = systemSettings.sysColorDisableBG;

                tvProductCat.LoadDataOnPageLoad = false;
                //Check user validity
                if (UserId <0)
                {
                    this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                    return;
                }
                int currentUserType = loginUserType;

                tvProductCat.textFldName = "description1";
                tvProductCat.valueFldName = "code";
                tvProductCat.parentFldName = "parentCode";
                tvProductCat.dataTableName = "tm_productCat";
                
                //If this is the first visit to the page, bind the role data to the datalist
                if (!Page.IsPostBack)
                {
                    tvProductCat.LoadData();

                    currentItemId = Null.NullInteger;
                    //Determine ItemId of Product to Update
                    if (this.Request.QueryString["requestId"] != null)
                    {
                        int tmp = 0;
                        if (!int.TryParse(this.Request.QueryString["requestId"], out tmp))
                        {
                            sysLibs.ShowErrorNotice(lblNotice, this.Request.QueryString["requestId"].ToString() + " không tồn tại");
                            return;
                        }
                        currentItemId = tmp;
                    }

                    if (currentItemId >0)
                    {
                        if (!LoadBuyRequest(currentItemId,UserId, userRoles.IsBuyRequestManager(currentUserType) ))
                            return;
                    }
                    else //truong hop them moi
                    {
                        currentItemId = AddBuyRequest();
                        if (currentItemId == Null.NullInteger)
                        {
                            pnlButton.Visible = false;
                            pnlThongTinChung.Visible = false;
                            pnlThongTinPhanLoai.Visible = false;
                            pnlThongTinQuanLy.Visible = false;
                            pnlMenu.Visible = false;
                            return;
                        }
                    }
                    setDefaultTab();
                }
                //Only manager role can access QUANLY tab
                lkQuanLy.Visible = userRoles.IsBuyRequestManager(currentUserType);
                pnlThongTinQuanLy.Visible = lkQuanLy.Visible;
               
                hplNgayDangKy.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtNgayDangKy);
                hplNgayHetHan.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtNgayHetHan);
            }
            catch (Exception exc) //Module failed to load
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());   
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                //Only attempt to delete the item if it exists already
                if (Null.IsNull(currentItemId)) return;
                buy_requestTA.Delete(currentItemId);
                //refresh cache
                SynchronizeModule();
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) 
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
        }
        
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                sysLibs.ShowErrorNotice(lblNotice, "");
                if (!doValidated()) return;
                if (DoUpdate(currentItemId))
                {
                    pnlMessage.Visible = true;
                    ctlMessage.Show("Đã lưu thông tin.", Globals.NavigateURL(this.TabId).ToString());
                }
                else
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Lưu thông tin gặp lỗi.");
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
        }
        protected void btnThuocLinhVuc_Click(object sender, EventArgs e)
        {
            if (Session["tm_ReturnArrayTT"] != null)
            {
                Hashtable tm_array = (Hashtable)Session["tm_ReturnArrayTT"];

                ddlThuocLinhVuc.DataSource = tm_array;
                ddlThuocLinhVuc.DataValueField = "Key";
                ddlThuocLinhVuc.DataTextField = "Value";
                ddlThuocLinhVuc.DataBind();

                Session.Remove("tm_ReturnArrayTT");
            }
        }
        protected void lkThongTinChung_Click(object sender, EventArgs e)
        {
            setDefaultTab();
        }
        protected void lkPhanLoai_Click(object sender, EventArgs e)
        {
            setPhanLoaiTab();
        }
        protected void lkQuanLy_Click(object sender, EventArgs e)
        {
            setQuanLyTab();
        }
        protected void btnChooseField_Click(object sender, EventArgs e)
        {
            try
            {
                Hashtable selectedNodes = sysLibs.GetHashTableSelectedNodes(tvProductCat.myTreeView);
                ddlThuocLinhVuc.Items.Clear();
                if (selectedNodes.Count <= 0) return;
                ddlThuocLinhVuc.DataSource = selectedNodes;
                ddlThuocLinhVuc.DataTextField = "Value";
                ddlThuocLinhVuc.DataValueField = "Key";
                ddlThuocLinhVuc.DataBind();
            }
            catch
            {
                sysLibs.ShowErrorNotice(lblNotice, "Thêm lĩnh vực lỗi");
                return;
            }
        }
        protected void btnGoToLastQuery_Click(object sender, EventArgs e)
        {
            int tabId = appLibs.GetTabIdByName(PortalSettings.PortalId, "buyRequest");
            int modId = appLibs.GetModuleIdByName(PortalSettings.PortalId, "buyRequest");
            string url = DotNetNuke.Common.Globals.NavigateURL(tabId, "search","mid=" + modId, "goLastList=1");
            Response.Redirect(url);
        }
        #endregion


        #region my function
        BuyRequestLibs sellExt = new BuyRequestLibs(sysLibs.GetConnectionString);
        private bool doValidated()
        {
            bool rs = true;
            int tmpYear;
            try
            {
                //if (!reqVNName.IsValid)
                if (txtTenVN.Text.Trim() == "" || !sysLibs.CheckStringSecurity(txtTenVN.Text.Trim()))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Tên sản phẩm không hợp lệ");
                    return false;
                }
                if (txtMoTa.Text.Trim() == "")
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Mô tả không hợp lệ");
                    return false;
                }
                
                if (!sysLibs.StringIsValidDateTime(txtNgayDangKy.Text.Trim()))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Ngày đăng ký không hợp lệ");
                    return false;
                }
                if (txtNgayHetHan.Text.Trim() !="" &&
                    !sysLibs.StringIsValidDateTime(txtNgayHetHan.Text.Trim()))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Ngày hết hạn không hợp lệ");
                    return false;
                }
                if (!sysLibs.CheckStringSecurity(txtThongTinKhac.Text))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Thông tin khác không hợp lệ");
                    return false;
                }
                if (!sysLibs.CheckStringSecurity(txtTuKhoa.Text))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Từ khóa không hợp lệ");
                    return false;
                }
                if (!sysLibs.CheckStringSecurity(txtNoiDungXuLy.Text))
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Nội dung xử lý không hợp lệ");
                    return false;
                }
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
            return rs;
        }

        private void setDDLLoaiMaSo()
        {
            try
            {
                DataTable dt = sellExt.GetProductType();
                ddlLoaiMaSo.Items.Clear();
                if (dt != null && dt.Rows.Count > 0)
                {
                    ddlLoaiMaSo.DataSource = dt;
                    ddlLoaiMaSo.DataTextField = "description1";
                    ddlLoaiMaSo.DataValueField = "code";
                }
                ddlLoaiMaSo.DataBind();

            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
        }
        private void setDDLTrangThai()
        {
            try
            {

                DataTable dt=null;
                dt = sellExt.GetBuyRequestStatus();
             
                ddlTrangThai.Items.Clear();
                if (dt != null && dt.Rows.Count > 0)
                {
                    ddlTrangThai.DataSource = dt;
                    ddlTrangThai.DataTextField = "description1";
                    ddlTrangThai.DataValueField = "statusCode";
                }
                ddlTrangThai.DataBind();
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
        }
        private void setCheckedValueForCheckBox(ArrayList arrCheckBox, char[] arrChar)
        {
            try
            {
                for (int i = 0; i < arrChar.Length; i++)
                {
                    if (arrCheckBox[i] == null) continue;
                    ((CheckBox)arrCheckBox[i]).Checked = arrChar[i].ToString() != "0";
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
        private byte getCheckBoxValue(ArrayList arrCheckBox)
        {
            byte rs = 0;
            try
            {
                for (int i = 0; i < arrCheckBox.Count; i++)
                {
                    if (((CheckBox)arrCheckBox[i]).Checked)
                    {
                        rs += (byte)Math.Pow(2, i);
                    }
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }

            return rs;
        }

        private void setDatTieuChuanCheckBox(byte standarLevel)
        {
            ArrayList arrCheckBox = new ArrayList();
            arrCheckBox.Add(ckTieuChuanVN);
            arrCheckBox.Add(ckTieuChuanNgoai);

            char[] arrChar = sysLibs.ConvertNumToBitMask((short)standarLevel).ToCharArray();

            setCheckedValueForCheckBox(arrCheckBox, arrChar);
        }

        private byte getDatTieuChuanCheckBox()
        {
            byte rs = 0;

            try
            {
                ArrayList arrCheckBox = new ArrayList();
                arrCheckBox.Add(ckTieuChuanVN);
                arrCheckBox.Add(ckTieuChuanNgoai);

                rs = getCheckBoxValue(arrCheckBox);
            }
            catch (Exception exc)
            {
                throw exc;
            }
            return rs;
        }

        private void setChuyenGiaoCheckBox(short tranferMethod)
        {
            ArrayList arrCheckBox = new ArrayList();
            arrCheckBox.Add(ckPatent);
            arrCheckBox.Add(ckBiQuyet);
            arrCheckBox.Add(ckLicense);
            arrCheckBox.Add(ckDaoTao);
            arrCheckBox.Add(ckTuVanDaoTao);
            arrCheckBox.Add(ckChiaKhoaTraoTay);
            arrCheckBox.Add(ckThoaThuanKhachHang);

            char[] arrChar = sysLibs.ConvertNumToBitMask((short)tranferMethod).ToCharArray();

            setCheckedValueForCheckBox(arrCheckBox, arrChar);
        }
        private byte getChuyenGiaoCheckBox()
        {
            byte rs = 0;

            try
            {
                ArrayList arrCheckBox = new ArrayList();
                arrCheckBox.Add(ckPatent);
                arrCheckBox.Add(ckBiQuyet);
                arrCheckBox.Add(ckLicense);
                arrCheckBox.Add(ckDaoTao);
                arrCheckBox.Add(ckTuVanDaoTao);
                arrCheckBox.Add(ckChiaKhoaTraoTay);
                arrCheckBox.Add(ckThoaThuanKhachHang);

                rs = getCheckBoxValue(arrCheckBox);
            }
            catch (Exception exc)
            {
                throw exc;
            }

            return rs;

        }

        private void getLinhVuc(int productID)
        {
            try
            {
                DataTable dt = sellExt.GetCategory(productID.ToString());

                ddlThuocLinhVuc.Items.Clear();
                if (dt != null && dt.Rows.Count != 0)
                {
                    ddlThuocLinhVuc.DataSource = dt;
                    ddlThuocLinhVuc.DataTextField = "description1";
                    ddlThuocLinhVuc.DataValueField = "code";
                }
                ddlThuocLinhVuc.DataBind();
            }
            catch {}
        }

        private ArrayList GetSelectedNodes(int itemId)
        {
            DataTable dt = sellExt.GetCategory(itemId.ToString());
            ArrayList ar = new ArrayList();
            try
            {
                if (dt.Rows.Count > 0)
                    for (int idx = 0; idx < dt.Rows.Count; idx++)
                        ar.Add(dt.Rows[idx]["code"].ToString());
                tvProductCat.SetSelectedNodes(ar);        
            }
            catch (Exception er)
            {
                Common.sysLibs.lastErrorMessage = er.Message;
            }
            return ar;
        }

        private bool SaveBuyRequestCat(string requestId)
        {
            try
            {
                DataTable dt = sellExt.GetCategory(requestId);

                //if (dt != null && dt.Rows.Count != 0)
                //{
                //    foreach (DataRow dr in dt.Rows)
                //    {
                //        string id = dr["syscodeId"].ToString();
                //        sellExt.DeleteCategory(id);
                //    }
                //}

                //return array List
                sellExt.DeleteCategoryByRequestId(requestId);
                ArrayList seletedNodes = new ArrayList();
                if (ddlThuocLinhVuc.Items.Count > 0)
                {
                    for (int idx = 0; idx < ddlThuocLinhVuc.Items.Count; idx++)
                        seletedNodes.Add(ddlThuocLinhVuc.Items[idx].Value);
                    seletedNodes = sysLibs.Translate(seletedNodes, "tm_productCat", "code", "syscodeId");
                    for (int idx = 0; idx < seletedNodes.Count; idx++)
                        sellExt.InsertCategory(requestId, seletedNodes[idx].ToString());
                }
                return true;
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
            return false; 
        }

        private bool CheckBuyRequestQuota(int userId, int maxNoBuyRequest)
        {
            int usedBuyRequestCount =  (int)buy_requestTA.TotalRequest(userId);
            return (usedBuyRequestCount < maxNoBuyRequest);
        }
        private data.applicationDataSet.tm_buy_requestRow GetUnusedBuyRequest()
        {
            buy_requestTA.FillByStatusNull(buy_requestTbl);
            if (buy_requestTbl.Count <= 0) return null;
            return buy_requestTbl[0];
        }


        /// <summary>
        ///  Add new buy request,try to use unused buy requests.
        /// </summary>
        /// <returns></returns>
        private int AddBuyRequest()
        {
            int maxBuyRequestNo = Common.appLibs.GetUserInfo(UserId).maxNoBuy;
            int unUsedBuyRequestId = Null.NullInteger;
            if (!CheckBuyRequestQuota(UserId, maxBuyRequestNo))
            {
                pnlMessage.Visible = true;
                ctlMessage.Show("Không thể thêm tìm mua mới : Số lượng giới hạn = " + maxBuyRequestNo.ToString(),
                                     Globals.NavigateURL(this.TabId).ToString());
                return Null.NullInteger;
            }
            //Use unused data if any
            buy_requestRow = GetUnusedBuyRequest();
            try
            {
                if (buy_requestRow == null)
                {
                    buy_requestTbl.Clear();
                    buy_requestRow = buy_requestTbl.Newtm_buy_requestRow();
                    buy_requestRow.RegisterBy  = UserId;
                    buy_requestRow.productCode = sysLibs.CreateItemId();
                    buy_requestRow.productType = "";
                    buy_requestRow.Name1 = "";
                    buy_requestRow.Description = "";
                    buy_requestRow.registerDate = DateTime.Now;
                   
                    buy_requestTbl.Addtm_buy_requestRow(buy_requestRow);
                    buy_requestTA.Update(buy_requestRow);
                }
                else buy_requestRow.RegisterBy = UserId;

                ShowBuyRequest(buy_requestRow);

                //an di nut xoa va chinh sua
                btnDelete.Visible = false;
                return buy_requestRow.requestId;
            }
            catch (Exception exc)
            {
                sysLibs.showSystemError(lblNotice, exc.ToString());
                ctlMessage.Show("Không thể thêm yêu cầu.", Globals.NavigateURL(this.TabId).ToString());
            }
            return Null.NullInteger;
        }

        private bool LoadBuyRequest(int itemId,int userId,bool isBRM)
        {
            try
            {
                buy_requestTA.FillByRequestId(buy_requestTbl, itemId);
                if (buy_requestTbl.Count<=0)
                {
                    sysLibs.ShowErrorNotice(lblNotice, "Không có sản phẩm yêu cầu.");
                    return false;
                }
                ShowBuyRequest(buy_requestTbl[0]);
                CheckEditable(buy_requestTbl[0], userId, isBRM);
                return true;
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
            return false;
        }

        private bool CheckEditable(data.applicationDataSet.tm_buy_requestRow buy_requestRow,int userId, bool isBRM)
        {
            if (buy_requestRow == null) return false;
            //Only manager can modify CLOSE data
            if (!isBRM && 
                !buy_requestRow.IsStatusNull() &&
                 buy_requestRow.Status == Common.consts.constStatusCLOSE)
            {
                btnUpdate.Visible = false; btnDelete.Visible = false;
                sysLibs.ShowErrorNotice(lblNotice, "Không thể thay đổi thông tin đã bị đóng.");
                btnUpdate.Visible = false; btnDelete.Visible = false;
                return false;
            }
            //Only manager or owner can modify data
            if (!isBRM && (buy_requestRow.RegisterBy != userId))
            {
                sysLibs.ShowErrorNotice(lblNotice, "Không thể thay đổi thông tin.");
                btnUpdate.Visible = false; btnDelete.Visible = false;
                return false;
            }
            return true;
        }

        private bool ShowBuyRequest(data.applicationDataSet.tm_buy_requestRow buy_requestRow)
        {
            try
            {
                txtMaSo.Text = buy_requestRow.productCode;
                txtTenVN.Text = (buy_requestRow.IsName1Null() ? "" : buy_requestRow.Name1); ;
                txtTenAnh.Text = (buy_requestRow.IsName2Null() ? "" : buy_requestRow.Name2);
                txtMoTa.Text = (buy_requestRow.IsDescriptionNull() ? "" : buy_requestRow.Description);

                if (!buy_requestRow.IsstandardLevelNull()) setDatTieuChuanCheckBox(buy_requestRow.standardLevel);
                txtSanXuatSauNam.Text = (buy_requestRow.IsproductYearNull() ? "" : buy_requestRow.productYear.ToString());
                txtTuKhoa.Text = (buy_requestRow.IsKeywordsNull() ? "" : buy_requestRow.Keywords);
                txtThongTinKhac.Text = (buy_requestRow.IsOtherInfoNull() ? "" : buy_requestRow.OtherInfo);

                //lay thong tin linh vuc va phan loai
                getLinhVuc(buy_requestRow.requestId);
                GetSelectedNodes(buy_requestRow.requestId);

                if (!buy_requestRow.IstransferMethodNull())
                    setChuyenGiaoCheckBox(buy_requestRow.transferMethod);

                lblOwnerId.Text = buy_requestRow.RegisterBy.ToString();

                //hien thi danh sach loai san pham
                setDDLLoaiMaSo();
                if (!buy_requestRow.IsproductTypeNull()) ddlLoaiMaSo.SelectedValue = buy_requestRow.productType.Trim();

                //trang thai
                setDDLTrangThai();
                if (!buy_requestRow.IsStatusNull()) ddlTrangThai.SelectedValue = buy_requestRow.Status.Trim();

                txtNgayDangKy.Text = (buy_requestRow.IsregisterDateNull() ? "" : buy_requestRow.registerDate.ToShortDateString());
                txtNgayHetHan.Text = (buy_requestRow.IsexpireDateNull() ? "" : buy_requestRow.expireDate.ToShortDateString());
                txtNgayCapnhat.Text = (buy_requestRow.IslastModifyDateNull() ? "" : buy_requestRow.lastModifyDate.ToShortDateString());
                txtNoiDungXuLy.Text = (buy_requestRow.IsProcessNotesNull() ? "" : buy_requestRow.ProcessNotes);

                txtNguoiDangKy.Text = Common.appLibs.GetUserInfo(buy_requestRow.RegisterBy).fullName;
                return true;
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
            return false;
        }

        private bool DoUpdate(int itemId)
        {
            try
            {
                buy_requestTA.FillByRequestId(buy_requestTbl, itemId);

                if (buy_requestTbl.Count <= 0)
                {
                    Common.sysLibs.ShowErrorNotice(lblNotice, "Không có dữ liệu yêu cầu.");
                    return false;
                }
                buy_requestRow = buy_requestTbl[0];
                bool fNewData = (buy_requestRow.IsStatusNull() || buy_requestRow.Status.Trim() == "");
                buy_requestRow.RegisterBy = Convert.ToInt32(lblOwnerId.Text);
                buy_requestRow.productCode = txtMaSo.Text.Trim();
                buy_requestRow.productType = ddlLoaiMaSo.SelectedValue.Trim();
                buy_requestRow.Name1 = txtTenVN.Text.Trim();
                buy_requestRow.Name2 = txtTenAnh.Text.Trim();
                buy_requestRow.Description = txtMoTa.Text.Trim();

                //nam hoan thien
                if (txtSanXuatSauNam.Text.Trim() != "")
                    buy_requestRow.productYear = Convert.ToInt16(txtSanXuatSauNam.Text.Trim());

                buy_requestRow.Keywords = txtTuKhoa.Text.Trim();
                buy_requestRow.OtherInfo = txtThongTinKhac.Text.Trim();

                //set tieu chuan
                buy_requestRow.standardLevel = getDatTieuChuanCheckBox();
                //chuyen giao
                buy_requestRow.transferMethod = getChuyenGiaoCheckBox();

                DateTime dt = DateTime.Today;
                if (DateTime.TryParse(txtNgayDangKy.Text.Trim(), out dt)) buy_requestRow.registerDate = dt;
                if (DateTime.TryParse(txtNgayHetHan.Text.Trim(), out dt)) buy_requestRow.expireDate = dt;
                buy_requestRow.ProcessNotes = txtNoiDungXuLy.Text.Trim();

                //Only update last modified date it was changed by owner
                if (UserId == buy_requestRow.RegisterBy) buy_requestRow.lastModifyDate = DateTime.Now;

                // ===========================================================
                // Set status 
                //  - New data : status = NEW 
                //  - Owner edit verified data : status = PENDING 
                //  - Product manager : use selected status
                //  - Other cases : donot change status
                // ===========================================================
                string lastStatus = "";
                if (fNewData) buy_requestRow.Status = consts.constStatusNEW;
                else
                {
                    lastStatus = buy_requestRow.Status;
                    if (pnlThongTinQuanLy.Visible && ddlTrangThai.Enabled) //Edit by manager or admin
                        buy_requestRow.Status = ddlTrangThai.SelectedValue.Trim();
                    else
                    {
                        if (buy_requestRow.Status != consts.constStatusNEW)
                        {
                            buy_requestRow.Status = consts.constStatusPENDING;
                        }
                    }
                }
                buy_requestTA.Update(buy_requestRow);
                
                //if (pnlThongTinQuanLy.Visible && ddlTrangThai.Enabled && buy_requestRow.Status != lastStatus)
                //    appLibs.MailChangeBuyRequestStatus(buy_requestRow.registerBy, buy_requestRow.name1, ddlTrangThai.SelectedItem.Text,"");
                //them thong tin linh vuc
                SaveBuyRequestCat(itemId.ToString());
                return true;
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowDebugMsg(lblDebugMessage, exc.Message.ToString());
            }
            return false;
        }

        private void setDefaultTab()
        {
            pnlThongTinChung.Visible    = true;
            pnlThongTinPhanLoai.Visible = false;
            pnlThongTinQuanLy.Visible   = false;
        }

        private void setPhanLoaiTab()
        {
            pnlThongTinChung.Visible    = false;
            pnlThongTinPhanLoai.Visible = true;
            pnlThongTinQuanLy.Visible   = false;
        }

        private void setQuanLyTab()
        {
            pnlThongTinChung.Visible    = false;
            pnlThongTinPhanLoai.Visible = false;
            pnlThongTinQuanLy.Visible   = true;
        }
        /// <summary>
        /// Get unused item code 
        /// </summary>
        /// <returns>  Null.NullInteger if error or do not have unused item</returns>
        #endregion
        
}
}

